// src/pages/RoleList/index.tsx
import React, { useState, useRef, useEffect } from 'react';
import { callApi, handleProTableRequest } from '@/utils/request';
import {
    PageContainer,
    ProTable,
    ProColumns,
} from '@ant-design/pro-components';
import {
    Button,
    Space,
    message,
    Modal,
    Form,
    Input,
    Card,
    Row,
    Col,
    Dropdown,
    SpaceProps,
} from 'antd';
import {
    PlusOutlined,
    DownOutlined,
    UserAddOutlined,
} from '@ant-design/icons';
import {
    getRoleList,
    deleteRole,
    getUserListByRole,
    addUserRole,
    deleteUserRole,
    deleteUserRoleBatch,
} from '@/services/roleUser';
import SelectUserModal from '@/pages/RoleList/components/SelectUserModal';
import {addRole, editRole} from "@/services/role";
import PermissionAssignDrawer from "@/pages/RoleList/components/PermissionAssignDrawer";
import AuthorizedButton from '@/components/AuthorizedButton';
import { RoleItem, RoleQueryParams } from '@/types/role';

const RoleUserList: React.FC = () => {
    const actionRef = useRef<any>(null);
    const [selectedRowsState, setSelectedRowsState] = useState<RoleItem[]>([]);
    const [roleModalVisible, setRoleModalVisible] = useState<boolean>(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [roleForm] = Form.useForm();
    const [userModalVisible, setUserModalVisible] = useState<boolean>(false);
    const [currentRole, setCurrentRole] = useState<RoleItem | undefined>();
    const [isEdit, setIsEdit] = useState<boolean>(false);
    const [disableSubmit, setDisableSubmit] = useState<boolean>(false);
    const [permissionDrawerVisible, setPermissionDrawerVisible] = useState(false);
    const [selectedRoleId, setSelectedRoleId] = useState<number | null>(null);

    // 角色列表列定义
    const roleColumns: ProColumns<RoleItem>[] = [
        {
            title: '角色ID',
            dataIndex: 'id',
            align: "center",
            width: 120,
            search: false,
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            align: "center",
            width: 150,
        },
        {
            title: '角色描述',
            dataIndex: 'description',
            align: "center",
            ellipsis: true,
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            align: "center",
            width: 150,
            render: (_, record) => (
                <Space>
                    <AuthorizedButton
                        type="link"
                        size="small"
                        onClick={() => handleOpenUserModal(record)}
                        code="role_list_set_user_btn" // 替换为实际权限码
                    >
                        设置用户
                    </AuthorizedButton>
                    <Dropdown
                        menu={{
                            items: [
                                {
                                    key: 'edit',
                                    label: '编辑',
                                    onClick: () => handleEditRole(record),
                                },
                                {
                                    key: 'delete',
                                    label: '删除',
                                    onClick: () => handleDeleteRole(record),
                                },
                                {
                                    key: 'assignPermission',
                                    label: '分配资源',
                                    onClick: () => handleBindPermission(record),
                                },
                            ],
                        }}
                        trigger={['click']}
                    >
                        <AuthorizedButton
                            type="link"
                            size="small"
                            code="role_list_more_btn" // 替换为实际权限码
                        >
                            更多 <DownOutlined />
                        </AuthorizedButton>
                    </Dropdown>
                </Space>
            ),
        },
    ];

    // 打开用户列表模态框
    const handleOpenUserModal = (record: RoleItem) => {
        setCurrentRole(record);
        setUserModalVisible(true);
    };

    // 添加角色
    const handleAddRole = () => {
        setIsEdit(false);
        setDisableSubmit(false);
        setCurrentRole(undefined);
        setRoleModalVisible(true);
    };

    // 编辑角色
    const handleEditRole = (record: RoleItem) => {
        setIsEdit(true);
        setDisableSubmit(false);
        setCurrentRole(record);
        roleForm.setFieldsValue({
            id: record.id,
            roleName: record.roleName,
            roleCode: record.roleCode,
            description: record.description
        });
        setRoleModalVisible(true);
    };

    // 删除角色
    const handleDeleteRole = (record: RoleItem) => {
        Modal.confirm({
            title: '确认删除',
            content: `您确定要删除角色 "${record.roleName}" 吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                const result = await callApi(
                    () => deleteRole({ id: record.id }),
                    { successMsg: '删除成功', errorMsg: '删除失败' }
                );

                if (result && actionRef.current) {
                    await actionRef.current.reload();
                }
            },
        });
    };

    // 删除角色
    const handleBindPermission = (record: RoleItem) => {
        setSelectedRoleId(record.id);
        setPermissionDrawerVisible(true);
    };

    // 角色模态框确认
    const handleRoleModalOk = async () => {
        try {
            const values = await roleForm.validateFields();
            setConfirmLoading(true);

            let result;
            if (isEdit && currentRole?.id) {
                result = await callApi(
                    () => editRole({ ...values, id: currentRole.id }),
                    { successMsg: '编辑成功', errorMsg: '编辑失败' }
                );
            } else {
                result = await callApi(
                    () => addRole(values),
                    { successMsg: '新增成功', errorMsg: '新增失败' }
                );
            }

            if (result) {
                setRoleModalVisible(false);
                if (actionRef.current) {
                    await actionRef.current.reload();
                }
            }
        } catch (error) {
            console.error('提交表单失败:', error);
        } finally {
            setConfirmLoading(false);
        }
    };

    // 角色模态框取消
    const handleRoleModalCancel = () => {
        setRoleModalVisible(false);
    };

    return (
        <PageContainer>
            <Card>
                <ProTable<RoleItem, RoleQueryParams>
                    actionRef={actionRef}
                    rowKey="id"
                    search={{
                        labelWidth: 'auto',
                    }}
                    toolBarRender={() => [
                        <AuthorizedButton
                            key="addRole"
                            type="primary"
                            onClick={handleAddRole}
                            code="role_list_add_btn" // 替换为实际权限码
                        >
                            <PlusOutlined />
                            新增角色
                        </AuthorizedButton>,
                    ]}
                    tableAlertRender={false}
                    request={async (params, sorter, filter) => {
                        const queryParams: RoleQueryParams = {
                            pageNum: params.current || 1,
                            pageSize: params.pageSize || 10,
                            roleName: params.roleName
                        };

                        return handleProTableRequest<RoleItem>(
                            () => getRoleList(queryParams),
                            { errorMsg: '获取角色列表失败' }
                        );
                    }}
                    columns={roleColumns}
                    rowSelection={{
                        onChange: (selectedRowKeys, selectedRows) => {
                            setSelectedRowsState(selectedRows);
                        },
                    }}
                    pagination={{
                        defaultPageSize: 10,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        pageSizeOptions: ['10', '20', '30'],
                    }}
                />
            </Card>

            {/* 添加角色模态框 */}
            <Modal
                title={isEdit ? '编辑角色' : '新增角色'}
                open={roleModalVisible}
                onOk={handleRoleModalOk}
                onCancel={handleRoleModalCancel}
                confirmLoading={confirmLoading}
                maskClosable={false}
                width={600}
            >
                <Form
                    form={roleForm}
                    layout="vertical"
                    disabled={disableSubmit}
                >
                    <Form.Item
                        name="roleName"
                        label="角色名称"
                        rules={[{ required: true, message: '请输入角色名称!' }]}
                    >
                        <Input placeholder="请输入角色名称" />
                    </Form.Item>
                    <Form.Item
                        name="description"
                        label="描述"
                    >
                        <Input.TextArea placeholder="请输入描述" rows={4} />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 用户列表模态框 */}
            {currentRole && (
                <SelectUserModal
                    visible={userModalVisible}
                    currentRoleId={currentRole.id}
                    currentRoleName={currentRole.roleName}
                    onOk={() => {
                        setUserModalVisible(false);
                    }}
                    onCancel={() => {
                        setUserModalVisible(false);
                    }}
                />
            )}

            {/* 权限分配抽屉 */}
            {selectedRoleId !== null && (
                <PermissionAssignDrawer
                    open={permissionDrawerVisible}
                    roleId={selectedRoleId}
                    onClose={() => setPermissionDrawerVisible(false)}
                    onSuccess={() => {
                        setPermissionDrawerVisible(false);
                        // 可选：刷新角色列表或提示
                        // message.success('权限分配成功');
                    }}
                />
            )}
        </PageContainer>
    );
};

export default RoleUserList;